package com.project;

import com.project.config.MVCConfig;
import com.project.filter.pushFilter;
import org.apache.catalina.Context;
import org.apache.catalina.Wrapper;
import org.apache.catalina.startup.Tomcat;
import org.apache.tomcat.util.descriptor.web.FilterDef;
import org.apache.tomcat.util.descriptor.web.FilterMap;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.Filter;
import javax.servlet.ServletContext;

public class MainForum {
    public MainForum(){
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(8088);
        tomcat.getConnector();

        Context webContext = tomcat.addContext("",null);

        this.registerFilter(webContext,new pushFilter(), "/topic/add","/res/add");

        //产生前端控制器对象
        DispatcherServlet dispatcher = new DispatcherServlet
                (this.getWebApplicationContext(webContext.getServletContext()));
        //注册前端控制器
        Wrapper w = Tomcat.addServlet(webContext,"springMVC",dispatcher);
        //容器启动即完成初始化
        w.setLoadOnStartup(0);
        //配置访问路径
        w.addMapping("/*");

        try {
            tomcat.start();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void registerFilter(Context webContext, Filter filterObj,String...urlPath){
        FilterDef def = new FilterDef();
        //设置过滤器类
        def.setFilter(filterObj);
        //设置过滤器名称
        def.setFilterName(filterObj.getClass().getSimpleName());

        webContext.addFilterDef(def);

        FilterMap map = new FilterMap();
        map.setFilterName(filterObj.getClass().getSimpleName());
        for (String path:urlPath){
            map.addURLPattern(path);
        }
        webContext.addFilterMap(map);
    }

    /**
     * 创建spring上下文容器
     * @param servletContext servlet上下文对象
     * @return spring上下文容器
     */
    private WebApplicationContext getWebApplicationContext(ServletContext servletContext){
        AnnotationConfigWebApplicationContext webApp = new AnnotationConfigWebApplicationContext();
        //设置配置类
        webApp.register(MVCConfig.class);
        //设置容器的上下文
        webApp.setServletContext(servletContext);

        webApp.refresh();
        webApp.registerShutdownHook();

        return webApp;
    }

    public static void main(String[] args) {
        new MainForum();
    }
}
